import axios from 'axios'
import {
    message
} from '@/utils/resetMessage';

import store from '../store'
import router from '@/router'

const getStore = name => {
    return localStorage.getItem(name);
}
// 创建axios实例
let service = axios.create({
    // baseURL: 'http://47.103.69.233:8199/', // api的base_url
    baseURL: 'http://47.103.69.233:80/', // api的base_url
    timeout: 10000 // 请求超时时间
})

service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
service.defaults.headers.put['Content-Type'] = 'application/json;charset=UTF-8';
// request拦截器
service.interceptors.request.use(config => {
    if (getStore("DEVELOPID")) {
        config.headers = {
            'Authorization': getStore("DEVELOPID"), //携带权限参数
            'Content-Type': 'application/json;charset=UTF-8'
        };
    }
    // showLoading();
    return config
}, error => {
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code:200,接口正常返回;
         */
        const res = response.data;
        if (res.ret !== 0) {
            // 根据服务端约定的状态码：1007:非法的token; 1006:Token 过期了;
            if (res.ret === 1007 || res.ret === 1006) {
                localStorage.removeItem("DEVELOPID")
                var this_router = location.hash.substr(1);
                console.log(store)
                console.log(this_router)
                if (this_router != '/home' && this_router != "/") {
                    router.push('/');
                }
                message({
                    message: "身份已过期，请重新登录！",
                    type: 'error',
                    duration: 3 * 1000
                });
            } else if (res.ret === 1046 || res.ret === 1052 || res.ret === 1019) {
                return response.data;
            } else {
                message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                })
            }
            return Promise.reject('error');
        } else { // res.ret === 0,正常返回数据
            return response.data
        }
    },
    error => {
        message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
        })
        return Promise.reject(error)
    }
)

export default service